<%@ include file="/common/taglibs.jsp" %>

<title><fmt:message key="userList.title"/></title>
	
<%--	
<meta name="author" content="jron" id="hateie"/>
<meta name="menu" content="AdminMenu"/>
<script language="JavaScript">
    
function getOs(){
    var OsObject = "";
   if(navigator.userAgent.indexOf("MSIE")>0) {
        return "MSIE";
   }
   if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
        return "Firefox";
   }
   if(isSafari=navigator.userAgent.indexOf("Safari")>0) {
        return "Safari";
   } 
   if(isCamino=navigator.userAgent.indexOf("Camino")>0){
        return "Camino";
   }
   if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){
        return "Gecko";
   }
}

</script> --%>


<link rel="stylesheet" type="text/css" href="../../../styles/ext-all.css"/>
<!-- LIBS -->
<script type="text/javascript" src="<c:url value='/scripts/ext/yui-utilities.js'/>"></script>
<script type="text/javascript" src="<c:url value='/scripts/ext/ext-yui-adapter.js'/>"></script>
<script type="text/javascript" src="<c:url value='/scripts/ext/date.js'/>"></script>
<!-- ENDLIBS -->

<script type="text/javascript" src="<c:url value='/scripts/ext/ext-all.js'/>"></script>
<script type="text/javascript" src="<c:url value='/scripts/json_cn.js'/>"></script>

<%--<script type="text/javascript" src="<c:url value='/scripts/jc/jrusersgrid.js'/>"></script>--%>
<link rel="stylesheet" type="text/css" href="../../../styles/examples.css"/>

<div id="nav" style="position: relative;width: 680px;">dddddddddddddddddddddd</div>

<div class="content">

    <div style="width:694px;" class="x-box-blue">
        <div class="x-box-tl">
            <div class="x-box-tr">
                <div class="x-box-tc"></div>
            </div>
        </div>
        <div class="x-box-ml">
            <div class="x-box-mr">
                <div class="x-box-mc">
                    <h3 style="margin-bottom:5px;"><fmt:message key="userList.heading"/></h3>

                    <%--<div id="grid-panel" style="width:100%;height:290px;">--%>
                    <div id="editor-grid"
                         style="border:1px solid #99bbe8;overflow: hidden; width: 665px; height: 300px;
                                position:relative;left:0;top:0;"></div>
                    <!--</div>-->
                    <%--
                        var layout = Ext.BorderLayout.create({
                            center: {
                                margins:{left:2,top:3,right:2,bottom:3},
                                panels: [new Ext.GridPanel(grid)]
                            }
                        }, 'grid-panel');
                    --%>
                </div>
            </div>
        </div>
        <div class="x-box-bl">
            <div class="x-box-br">
                <div class="x-box-bc"></div>
            </div>
        </div>
    </div>

    <br>

    <!-- Add Account Dialog -->
    <div id="a-addInstance-dlg" style="visibility:hidden;">
        <div class="x-dlg-hd">Add New Account</div>
        <div class="x-dlg-bd">
            <div id="a-addInstance-inner" class="x-layout-inactive-content">
                <div id="a-addInstance-form"></div>
            </div>
        </div>
    </div>

    <!-- Add update Account Dialog -->
    <div id="a-updateInstance-dlg" style="visibility:hidden;">
        <div class="x-dlg-hd">Update Account</div>
        <div class="x-dlg-bd">
            <div id="a-updateInstance-inner" class="x-layout-inactive-content">
                <div id="a-updateInstance-form"></div>
            </div>
        </div>
    </div>

</div>

<script type="text/javascript">

Ext.onReady(function() {
    var jpageSize = 1;
    var filerTxt = "jron";

        // shorthand alias
    var fm = Ext.form,Ed = Ext.grid.GridEditor;

        // enable the QuickTips for the later Pagebar
    Ext.QuickTips.init();

    function formatBoolean(value) {
        return value ? 'Yes' : 'No';
    }

    function formatDates(value) {
        return value ? formatDate(new Date(value["time"]),"yyyy-MM-dd HH:mm:ss a"): '';
    }


    /************************************************************
     * Display the result in page
     * the column model has information about grid columns
     * dataIndex maps the column to the specific data field in
     * the data store (created below)
     ************************************************************/
    var cm = new Ext.grid.ColumnModel([{
        id: 'id',
        header: "Identify",
        dataIndex: 'id',
        width: 150,
        hidden:true
    },{
        header: "Username",
        dataIndex:'username',
        width:150
    },{
        header:"E-mail",
        dataIndex:'email',
        width:150
    },{
        header:"City",
        dataIndex:'address.city',
        width:150
    },{
        header:"Signup Date",
        dataIndex:'regDate',
        width:140,
        render:formatDates
    }]);

    cm.defaultSortable = true;

    var NewAccount = Ext.data.Record.create([
    {name: 'id', type: 'int'},
//    {name: 'date', mapping: 'regDate', type: 'date',convert :formatDates},
    {name: 'regDate', mapping: 'regDate', type: 'date',convert :formatDates},
    {name: 'username', type: 'string'},
    {name: 'email', type: 'string'},
    {name: "address.city", mapping:"address.city", type: "string"}
            ]);

    /************************************************************
     * connect to backend - grid - core part
     * create the Data Store
     *   connect with backend and list the result in page
     *   through JSON format
     ************************************************************/
    var ds = new Ext.data.Store({
        proxy:new Ext.data.ScriptTagProxy({
            url: '/admin/jsonusers.html?ajax=true'
        }),

        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'totalCount',
            id: 'id'
        },NewAccount 
                /*[
        {name:'id'},
        {name:'username'},
        {name:'regDate',type:'date', dateFormat: 'timestamp'},
        {name:'email'},
        {name: "city", mapping:"address.city", type: "string"}
                ]*/
                ),
        remoteSort:true
    });
    ds.setDefaultSort('regDate', 'DESC');

    var grid = new Ext.grid.EditorGrid('editor-grid', {
        ds:ds,
        cm:cm,
    //singleSelect singleSelect : Boolean True to allow selection of only one row at a time (defaults to false)
        selModel:new Ext.grid.RowSelectionModel({singleSelect:false}),
        enableColLock:false
    });


    // make the grid resizable, do before render for better performance
    var rz = new Ext.Resizable('editor-grid', {
        wrap:true,
        minHeight:100,
        pinned:true,
        handles: 's'
    });
    rz.on('resize', grid.autoSize, grid);

    // render it
    grid.render();

    /************************************************************
     * create header panel
     * add filter field - search function
     ************************************************************/
    var gridHeader = grid.getView().getHeaderPanel(true);
    var tb = new Ext.Toolbar(gridHeader);

    filterBtn = new Ext.Toolbar.MenuButton({
        icon: 'images/topic.gif',
        cls: 'x-btn-text-icon',
        text: 'Choose Filter',
        tooltip: 'Select one of filter',
        menu: {items: [
                new Ext.menu.CheckItem({ text: 'City', value: 'address.city', checked: false, group: 'filter', checkHandler: onItemCheck }),
                new Ext.menu.CheckItem({ text: 'E-mail', value: 'email', checked: false, group: 'filter', checkHandler: onItemCheck }),
                new Ext.menu.CheckItem({ text: 'Username', value: 'username', checked: false, group: 'filter', checkHandler: onItemCheck })
                ]},
        minWidth: 105
    });
    tb.add(filterBtn);

    // Create the filter field
    var filter = Ext.get(tb.addDom({ // add a DomHelper config to the toolbar and return a reference to it
        tag: 'input',
        type: 'text',
        size: '30',
        value: '',
        style: 'background: #F0F0F9;'
    }).el);

    // press enter keyboard
    filter.on('keypress', function(e) { // setup an onkeypress event handler
        if (e.getKey() == e.ENTER && this.getValue().length > 0 && filerTxt != "jron") {// listen for the ENTER key
            ds.load({params:{start:0, limit:jpageSize}});
        }
    });

    filter.on('keyup', function(e) { // setup an onkeyup event handler
        if (e.getKey() == e.BACKSPACE && this.getValue().length === 0 && filerTxt != "jron") {// listen for the BACKSPACE key and the field being empty
            ds.load({params:{start:0, limit:jpageSize}});
        }
    });

    // Update search button text with selected item
    function onItemCheck(item, checked)
    {
        if (checked) {
            filterBtn.setText(item.text + ':');
            filerTxt = item.value;
        }
    }

    /************************************************************
     * create footer panel
     *    actions and paging
     ************************************************************/
    var gridFoot = grid.getView().getFooterPanel(true);

    // add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: jpageSize,
        displayInfo: true,
        displayMsg: 'total {2} results found. Current shows {0} - {1}',
        emptyMsg: "not result to display"
    });
    // add the detailed add button
    paging.add('-', {
        pressed: true,
        enableToggle:true,
        text: 'Add',
        cls: '',
        toggleHandler: doAdd
    });
    // add the detailed delete button
    paging.add('-', {
        pressed: true,
        enableToggle:true,
        text: 'Delete',
        cls: '',
        toggleHandler: doDel
    });
    // --- end -- create foot panel

    /************************************************************
     * load parameter to backend
     *    have beforelaod function
     ************************************************************/
    ds.on('beforeload', function() {
        ds.baseParams = { // modify the baseParams setting for this request
            filterValue: filter.getValue(),// retrieve the value of the filter input and assign it to a property named filter
//            filterTxt: filterBtn.getText()
            filterTxt: filerTxt
        };
    });
    // trigger the data store load
    ds.load({params:{start:0, limit:jpageSize}});

    /************************************************************
     * Action - delete
     *   start to handle delete function
     *   need confirm to delete
     ************************************************************/
    function doDel() {
        var m = grid.getSelections();
        if (m.length > 0) {
            Ext.MessageBox.confirm('Message', 'Do you really want to delete them?', doDel2);
        } else {
            Ext.MessageBox.alert('Error', 'Please select at least one item to delete');
        }
    }

    function doDel2(btn) {
        if (btn == 'yes') {
            var m = grid.getSelections();
            var jsonData = "[";
            for (var i = 0,len = m.length; i < len; i++) {
                var ss = "{\"id\":\"" + m[i].get("id") + "\"}";
                //alert(ss);
                if (i == 0)
                    jsonData = jsonData + ss;
                else
                    jsonData = jsonData + "," + ss;
                ds.remove(m[i]);
            }
            jsonData = jsonData + "]";
            ds.load({params:{start:0, limit:jpageSize, delData:jsonData}});
        }
    }

    /************************************************************
     *  Add an "clickoutside" event to a Grid.
     *     @param grid {Ext.grid.Grid} The grid to add a clickoutside event to.
     *     The handler is passed the Event and the Grid.
     ************************************************************/
    function addClickOutsideEvent(grid) {
        if (!grid.events.clickoutside) {
            grid.addEvents({"clickoutside": true});
        }
        if (!Ext.grid.Grid.prototype.handleClickOutside) {
            Ext.grid.Grid.override({
                handleClickOutside: function(e) {
                    var p = Ext.get(e.getTarget()).findParent(".x-grid-container");
                    if (p != this.container.dom) {
                        this.fireEvent("clickoutside", e, grid);
                    }
                }
            });
        }
        Ext.get(document.body).on("click", grid.handleClickOutside, grid);
    }

    /************************************************************
     * Create a new dialog - reuse by create and edit part
     ************************************************************/
    function createNewDialog(dialogName) {
        var thisDialog = new Ext.LayoutDialog(dialogName, {
            modal:true,
            autoTabs:true,
            proxyDrag:true,
            resizable:false,
            width: 480,
            height: 302,
            shadow:true,
            center: {
                autoScroll: true,
                tabPosition: 'top',
                closeOnTab: true,
                alwaysShowTabs: false
            }
        });
        thisDialog.addKeyListener(27, thisDialog.hide, thisDialog);
        thisDialog.addButton('Cancel', function() {
            thisDialog.hide();
        });

        return thisDialog;
    }
    ;

    /************************************************************
     * Action - update
     *   handle double click
     *   user select one of the item and want to update it
     ************************************************************/
    grid.on('rowdblclick', function(grid, rowIndex, e) {
        var selectedId = ds.data.items[rowIndex].id;

            // get information from DB and set form now...
        var account_data = new Ext.data.Store({
            proxy: new Ext.data.ScriptTagProxy({url:'/admin/jsonusers!jsonUser.html?ajax=true&id=' + selectedId}),
            reader: new Ext.data.JsonReader({}, 
            ['id','firstName','password','username','lastName']),
            remoteSort: false
        });
        

        account_data.on('load', function() {

            // set value now
            var updateId = account_data.getAt(0).data['id'];
            username_show.setValue(account_data.getAt(0).data['username']);
            firstname_show.setValue(account_data.getAt(0).data['firstName']);
            lastname_show.setValue(account_data.getAt(0).data['lastName']);
            password_show.setValue(account_data.getAt(0).data['password']);
            cPassword_show.setValue(account_data.getAt(0).data['password']);

            var updateInstanceDlg;
            if (!updateInstanceDlg) {
                updateInstanceDlg = createNewDialog("a-updateInstance-dlg");
                updateInstanceDlg.addButton('Save', function() {
                    // validation now
                    if (password_show.getValue() != cPassword_show.getValue()) {
                        password_show.markInvalid("passwords not match");
                        password_show.focus();
                        return;
                    }

                        // submit now... all the form information are submit to the server
                    // handle response after that...
                    if (form_instance_update.isValid()) {
                        form_instance_update.submit({
                            params:{id : updateId},
                            waitMsg:'Updating this account now...',
                            reset: false,
                            failure: function(form_instance_update, action) {
                                Ext.MessageBox.alert('Error Message', action.result.errorInfo);
                            },
                            success: function(form_instance_update, action) {
                                Ext.MessageBox.alert('Confirm', action.result.info);
                                updateInstanceDlg.hide();
                                ds.load({params:{start:0, limit:jpageSize}});
                            }
                        });
                    } else {
                        Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
                    }
                });

                var layout = updateInstanceDlg.getLayout();
                layout.beginUpdate();
                layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: 'Update Account'}));
                layout.endUpdate();

                updateInstanceDlg.show();
            }
        });

        account_data.load();
    });

    /************************************************************
     * Action - add
     *   start to handle add function
     *   new page appear and allow to submit
     ************************************************************/

    /************************************************************
     *  To create add new account dialog now....
     ************************************************************/
    function doAdd() {
        var aAddInstanceDlg;

        if (!aAddInstanceDlg) {
            aAddInstanceDlg = createNewDialog("a-addInstance-dlg");
            aAddInstanceDlg.addButton('Reset', resetForm, aAddInstanceDlg);
            aAddInstanceDlg.addButton('Save', function() {
                // validation now
                if (password_tf.getValue() != cPassword_tf.getValue()) {
                    password_tf.markInvalid("passwords not match");
                    password_tf.focus();
                    return;
                }

		    	// submit now... all the form information are submit to the server
                // handle response after that...
                if (form_instance_create.isValid()) {
                    form_instance_create.submit({
                        waitMsg:'Creating new account now...',
                        reset: false,
                        failure: function(form_instance_create, action) {
                            Ext.MessageBox.alert('Error Message', action.result.errorInfo);
                        },
                        success: function(form_instance_create, action) {
                            Ext.MessageBox.alert('Confirm', action.result.info);
                            aAddInstanceDlg.hide();
                            ds.load({params:{start:0, limit:jpageSize}});
                        }
                    });
                } else {
                    Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
                }
            });

            var layout = aAddInstanceDlg.getLayout();
            layout.beginUpdate();
            layout.add('center', new Ext.ContentPanel('a-addInstance-inner', {title: 'create account'}));
            layout.endUpdate();

            aAddInstanceDlg.show();
        }
        ;
    }

    /************************************************************
     * Form information - pop-up dialog
     * turn on validation errors beside the field globally
     ************************************************************/
    Ext.form.Field.prototype.msgTarget = 'side';
    Ext.form.Field.prototype.height = 20;
    Ext.form.Field.prototype.fieldClass = 'text-field-default';
    Ext.form.Field.prototype.focusClass = 'text-field-focus';
    Ext.form.Field.prototype.invalidClass = 'text-field-invalid';

    /************************************************************
     * Create new form to hold user enter information
     * This form is used to create new instance
     ************************************************************/
    var username_tf = new Ext.form.TextField({
        fieldLabel: 'Username',
        name: 'username',
        allowBlank:false
    });
    var password_tf = new Ext.form.TextField({
        fieldLabel: 'Password',
        name: 'password',
        inputType: 'password',
        allowBlank:false
    });
    var cPassword_tf = new Ext.form.TextField({
        fieldLabel: 'Confirm Password',
        name: 'confirmPassword',
        inputType: 'password',
        allowBlank:false
    });
    var firstname_tf = new Ext.form.TextField({
        fieldLabel: 'First Name',
        name: 'firstName'
    });
    var lastname_tf = new Ext.form.TextField({
        fieldLabel: 'Last Name',
        name: 'lastName'
    });
    var form_instance_create = new Ext.form.Form({
        labelAlign: 'right',
        url:'/admin/jsonusers!jsonSaveUser.html?ajax=true'
    });

    form_instance_create.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'});
    form_instance_create.fieldset(
    {id:'desc', legend:'Please fill the field'},
            username_tf,
            password_tf,
            cPassword_tf,
            firstname_tf,
            lastname_tf
            );

    form_instance_create.applyIfToFields({width:255});
    form_instance_create.render('a-addInstance-form');
    form_instance_create.end();

    resetForm = function() {
        username_tf.setValue('');
        password_tf.setValue('');
        cPassword_tf.setValue('');
        firstname_tf.setValue('');
        lastname_tf.setValue('');
    };


    /************************************************************
     * Create form to hold user enter information
     * This form is used to update current instance
     ************************************************************/
    var username_show = new Ext.form.TextField({
    // labelStyle: 'display: none',
        fieldLabel: 'Username',
        name: 'username',
        readOnly: true
    });
    var password_show = new Ext.form.TextField({
        inputType: 'password',
        fieldLabel: 'Password',
        name: 'password',
        allowBlank:false
    });
    var cPassword_show = new Ext.form.TextField({
        inputType: 'password',
        fieldLabel: 'Confirm Password',
        name: 'confirmPassword',
        allowBlank:false
    });
    var firstname_show = new Ext.form.TextField({
        fieldLabel: 'First Name',
        name: 'firstName'
    });
    var lastname_show = new Ext.form.TextField({
        fieldLabel: 'Last Name',
        name: 'lastName'
    });
    var form_instance_update = new Ext.form.Form({
        labelAlign: 'right',
        url:'/admin/jsonusers!jsonUpdateUser.html?ajax=true&from=JronExt'
    });

    form_instance_update.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'});
    form_instance_update.fieldset(
    {id:'', legend:'Please update the field'},
            username_show,
            password_show,
            cPassword_show,
            lastname_show,
            firstname_show
            );

    form_instance_update.applyIfToFields({width:255});
    form_instance_update.render('a-updateInstance-form');
    form_instance_update.end();

});

</script>